package top.system.dept.service;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import top.system.dept.mapper.ThingOrderMapper;
import top.system.dept.pojo.ThingOrder;
import top.system.dept.utils.MapUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: ScheduledService
 * @Author: Amosen
 * @Since: 2021/5/31
 */

// 定时服务，用于提供定时处理功能
// @Service
public class ScheduledService {

    @Autowired
    ThingOrderMapper orderMapper;

    @Autowired
    ThingOrderService orderService;

    @Autowired
    MailService mailService;

    @Value("${mail.orderExpire.template}")
    private String orderExpireTemplate;

    @Value("${order.status.SUBMITTED}")
    public String SUBMITTED = "已提交";
    @Value("${order.status.PASSED}")
    public String PASSED = "审核已通过";
    @Value("${order.status.NO_PASS}")
    public String NO_PASS = "审核未通过";
    @Value("${order.status.PREPARING}")
    public String PREPARING = "已移交";
    @Value("${order.status.PREPARED}")
    public String PREPARED = "已准备";
    @Value("${order.status.RETURNED}")
    public String RETURNED = "已归还";
    @Value("${order.status.DONE}")
    public String DONE = "已完成";

    // 每天早上6:00触发这个任务
    @Scheduled(cron = "0 0 6 * * ?")
    private void checkReturnOrder() { // 这个定时任务在每天早上六点检查是否有已过期未归还的工单，如果有，则发送邮件提示
        List<ThingOrder> orders = orderMapper.getOrderByStatus(PREPARED); // 获取已准备但未归还工单
        final Date now = new Date();
        final long nowTime = now.getTime();
        Map<Integer, Boolean> sent = new HashMap<>();
        for (ThingOrder order : orders) {
            final long orderTime = order.getReturnDate().getTime();
            if (orderTime < nowTime) { // 订单过期
                // 异步下发通知归还物资，完成工单
                new Thread(() -> {
                    if (!sent.get(order.getApplyUser().getId())) {
                        Map<String, Object> templateData = MapUtil.obj2Map(order);
                        try {
                            mailService.sendMail("工单过期提醒", order.getApplyUser().getMail(), templateData, orderExpireTemplate);
                            sent.put(order.getApplyUser().getId(), true);
                        } catch (Exception e) {
                            sent.put(order.getApplyUser().getId(), false);
                        }
                    }
                }).start();
            }
        }
    }

}
